﻿using Group3.MediaTool.Data.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Group3.MediaTool.Data.Generator
{
    public class LoadPrepare
    {
        //StringBuilder text;
        String text;
        List<LoaderMapping> replaceTexts = new List<LoaderMapping>();

        private void getReplaceTexts(string replaceTextPath)
        {
            if (!File.Exists(replaceTextPath))
            {
                DataDefinitionIO ddio = new DataDefinitionIO();
                ddio.writeLogFile("No replacements defined for " + replaceTextPath, "Info");
                return;
            }

            String[] texts = File.ReadAllLines(replaceTextPath);
            foreach (string s in texts)
            {
                string[] parts = s.Split(',');

                LoaderMapping lm = new LoaderMapping();
                lm.oldAttriuteName = parts[0];
                lm.attribute = parts[1];
                if (parts.Count() > 2)
                {
                    lm.referenceClass = parts[2];
                    lm.referenceTable = parts[3];
                    if (parts.Count() == 5)
                    {
                        lm.multiValParent = parts[4];
                    }
                }
                replaceTexts.Add(lm);
            }

        }

        public void updateImportfile(String filePath, string className)
        {
            //string file = filePath;
            string newFile = Path.Combine(StaticConfig.pathDataDefinition, StaticConfig.identifierData + className + ".xml");
            string tempFile = Path.Combine(StaticConfig.pathDataDefinition, StaticConfig.identifierData + className + "_Temp.tmp");
            string replaceFile = Path.Combine(StaticConfig.pathDataDefinition, StaticConfig.identifierReplace + className + ".txt");

            getReplaceTexts(replaceFile);

            String s = File.ReadAllText(filePath);
            text = s;//new StringBuilder(s);
            string mappingDetail = "<data><MAPPINGS>";

            foreach (LoaderMapping val in replaceTexts)
            {
                string replaceOpen = "<" + val.oldAttriuteName + ">";
                string replaceNoValue = "<" + val.oldAttriuteName + "/>";
                string replaceClosed = "</" + val.oldAttriuteName + ">";

                string valueOpen = "";
                string valueNoValue = "";
                string valueClosed = "";
                if (val.ToString() == "--1--")
                {
                    valueOpen = "<" + val.attribute + ">";
                    valueNoValue = "<" + val.attribute + "/>";
                    valueClosed = "</" + val.attribute + ">";

                    text = Regex.Replace(text, replaceOpen, valueOpen, RegexOptions.IgnoreCase);
                    text = Regex.Replace(text, replaceClosed, valueClosed, RegexOptions.IgnoreCase);
                }
                else
                {
                    mappingDetail += val.ToString();

                    valueOpen = "<REF_" + val.attribute + ">";
                    valueNoValue = "<REF_" + val.attribute + "/>";
                    valueClosed = "</REF_" + val.attribute + ">";

                    if (!String.IsNullOrEmpty(val.multiValParent))
                    {
                        text = text.Replace("<" + val.multiValParent + ">", "");
                        text = text.Replace("</" + val.multiValParent + ">", "");
                        text = text.Replace("<" + val.multiValParent + "/>", "");

                        text = Regex.Replace(text, replaceOpen + @"[^\<]+<name>", valueOpen, RegexOptions.IgnoreCase);
                        text = Regex.Replace(text, @"</name>[^\<]+" + replaceClosed, valueClosed, RegexOptions.IgnoreCase);
                    }
                    else
                    {
                        text = Regex.Replace(text, replaceOpen, valueOpen, RegexOptions.IgnoreCase);
                        text = Regex.Replace(text, replaceClosed, valueClosed, RegexOptions.IgnoreCase);
                    }
                }
                text = text.Replace(replaceNoValue, valueNoValue);
            }
            mappingDetail += "</MAPPINGS>";
            File.WriteAllText(tempFile, text);

            String[] addMapping = File.ReadAllLines(tempFile);
            File.Delete(tempFile);

            if (File.Exists(newFile))
            {
                File.Delete(newFile);
            }
            else
            {
                File.Create(newFile);
            }

            using (System.IO.StreamWriter file = File.AppendText(newFile))
            {
                int counter = 1;
                foreach (string line in addMapping)
                {
                    if (counter == 2)
                    {
                        file.Write(mappingDetail);
                    }
                    file.WriteLine(line);
                    counter++;
                }
                file.Write("</data>");
            }
        }
    }

    public class LoaderMapping
    {
        public String oldAttriuteName { get; set; }
        public String attribute { get; set; }
        public String referenceClass { get; set; }
        public String referenceTable { get; set; }
        public String multiValParent { get; set; }

        public override string ToString()
        {
            if(String.IsNullOrEmpty(referenceClass) && String.IsNullOrEmpty(referenceTable))
            {
                return "--1--";
            }

            string returnVal = "";
            returnVal += "<MAP>" + Environment.NewLine;
            returnVal += "  <Attr>REF_" + attribute + "</Attr>" + Environment.NewLine;
            returnVal += "  <RefClass>" + referenceClass + "</RefClass>" + Environment.NewLine;
            returnVal += "  <RefTab>" + referenceTable + "</RefTab>" + Environment.NewLine;

            if (!String.IsNullOrEmpty(multiValParent))
            {
                returnVal += "  <RefMultiParent>" + multiValParent + "</RefMultiParent>" + Environment.NewLine;
            }
            else
            {
                returnVal += "  <RefMultiParent/>" + Environment.NewLine;
            }

            returnVal += "</MAP>" + Environment.NewLine;
            return returnVal;
        }
    }
}
